package org.jfonia.connect5.relations;

import org.jfonia.connect5.basics.MutableValueNode;
import org.jfonia.connect5.basics.ValueNode;
import org.jfonia.connect5.basics.Node;

/**
 * ternary relation which updates c if a or b are changed and b is c is changed
 *
 * @author wijnand.schepens@hogent.be
 */
public abstract class ABCRelation<R, S, T> implements Relation
{
	protected ValueNode<R> a;
	protected MutableValueNode<S> b;
	protected MutableValueNode<T> c;

	public ABCRelation(ValueNode<R> a, MutableValueNode<S> b, MutableValueNode<T> c)
	{
		this.a = a;
		this.b = b;
		this.c = c;
		switchOn();
	}

	public void switchOn()
	{
		a.addObserver(this);
		b.addObserver(this);
		c.addObserver(this);
		updateC();
	}

	public void switchOff()
	{
		a.removeObserver(this);
		b.removeObserver(this);
		c.removeObserver(this);
	}


	public abstract void updateC();

	public abstract void updateB();

	public void onNotify(Object source)
	{
		if (source == a || source == b)
			updateC();
		else if (source == c)
			updateB();
		else
			throw new RuntimeException("Unknown source");
	}

}
